import { ref, computed, onMounted, nextTick } from 'vue'
import type { Ref } from 'vue'
import type { FormInstance } from 'element-plus'
import { ElMessage } from 'element-plus'
import type { UserInfo } from '@/interface/UserInfo'
import axios from 'axios'



// 只定义表单需要的字段和类型，严格对应你的接口字段，isPoor为number
interface RegisterForm {
      username: string
      tel: string
      email: string
      role: string
      school: string
      isPoor: number
      poorFile: string
      password: string
      confirmPassword: string
}

export function useRegisterForm() {
      // 指定 registerRef 类型，防止 null 报错
      const registerRef: Ref<FormInstance | null> = ref(null)

      // 指定 fileList 类型为 File 数组，防止 any[] 赋值到 never[] 的错误
      const fileList = ref<any[]>([])

      const registerForm = ref<RegisterForm>({
            username: '',
            tel: '',
            email: '',
            role: '',
            school: '',
            isPoor: 0, // 贫困状态 0 或 1
            poorFile: '',
            password: '',
            confirmPassword: ''
      })


      async function REQ_registerUser(form: RegisterForm, files?: File[]) {
            const formData = new FormData()
            formData.append('username', form.username)
            formData.append('tel', form.tel)
            formData.append('email', form.email)
            formData.append('role', form.role)
            formData.append('school', form.school)
            formData.append('isPoor', String(form.isPoor))
            formData.append('password', form.password)
            formData.append('confirmPassword', form.confirmPassword)

            fileList.value.forEach(file => {
                  if (file.raw) {
                        formData.append("poorFile", file.raw);
                  }  // 注意上传文件对象是 file.raw，不是 file 本身
            })



            // 后端接口地址请根据实际情况替换
            return axios.post('/api/login/register', formData)
      }

      const showStudentFields = computed(() => registerForm.value.role === '1')
      const showFileUpload = computed(() => showStudentFields.value && registerForm.value.isPoor === 1)

      const onRoleChange = (val: string) => {
            if (val !== '1') {
                  registerForm.value.school = ''
                  registerForm.value.isPoor = 0
                  registerForm.value.poorFile = ''
                  fileList.value = []
            }
      }

      const handleFileChange = (file: File, fileListParam: File[]) => {
            fileList.value = fileListParam
            if (fileListParam.length > 0) {
                  registerForm.value.poorFile = file.name
            } else {
                  registerForm.value.poorFile = ''
            }
      }

      const handleFileRemove = (_file: File, fileListParam: File[]) => {
            fileList.value = fileListParam
            if (fileListParam.length === 0) {
                  registerForm.value.poorFile = ''
            }
      }

      const rules = {
            role: [{ required: true, message: '请选择用户类型', trigger: 'change' }],
            username: [
                  { required: true, message: '请输入用户名', trigger: 'blur' },
                  { min: 3, max: 15, message: '用户名长度为3-15个字符', trigger: 'blur' }
            ],
            tel: [
                  { required: true, message: '请输入手机号', trigger: 'blur' },
                  { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
            ],
            email: [
                  { required: true, message: '请输入邮箱', trigger: 'blur' },
                  { type: 'email', message: '邮箱格式不正确', trigger: 'blur' }
            ],
            school: [
                  {
                        validator: (_rule: any, value: string, callback: (error?: Error) => void) => {
                              if (showStudentFields.value && !value) {
                                    callback(new Error('请输入学校'))
                              } else {
                                    callback()
                              }
                        },
                        trigger: 'blur'
                  }
            ],
            password: [
                  { required: true, message: '请输入密码', trigger: 'blur' },
                  { min: 6, message: '密码不能少于6位', trigger: 'blur' }
            ],
            confirmPassword: [
                  { required: true, message: '请确认密码', trigger: 'blur' },
                  {
                        validator: (_rule: any, value: string, callback: (error?: Error) => void) => {
                              if (value !== registerForm.value.password) {
                                    callback(new Error('两次输入密码不一致'))
                              } else {
                                    callback()
                              }
                        },
                        trigger: 'blur'
                  }
            ]
      }

      // 提交表单，registerRef.value 可能为 null，需判断后调用
      const submitForm = (): Promise<RegisterForm> => {
            return new Promise((resolve, reject) => {
                  if (!registerRef.value) {
                        reject(new Error('表单实例未绑定'))
                        return
                  }

                  registerRef.value.validate(async (valid: boolean) => {
                        if (valid) {
                              try {
                                    const uploadFile = fileList.value.length > 0 ? fileList.value[0] : undefined

                                    // 调用后端接口
                                    await REQ_registerUser(registerForm.value, uploadFile)

                                    ElMessage.success('注册成功！')
                                    resolve(registerForm.value)

                                    // 重置表单数据
                                    resetRegisterForm()
                              } catch (error: any) {
                                    ElMessage.error(error.response?.data?.message || '注册失败，请稍后重试')
                                    reject(error)
                              }
                        } else {
                              ElMessage.error('请正确填写表单信息')
                              reject(new Error('表单校验失败'))
                        }
                  })
            })
      }




      const resetRegisterForm = () => {
            Object.assign(registerForm.value, {
                  username: '',
                  tel: '',
                  email: '',
                  role: '',
                  school: '',
                  isPoor: 0,
                  poorFile: '',
                  password: '',
                  confirmPassword: ''
            })
            fileList.value = []
      }


      onMounted(() => {
            nextTick(() => {
                  resetRegisterForm()
            })
      })

      return {
            registerRef,
            registerForm,
            rules,
            fileList,
            showStudentFields,
            showFileUpload,
            onRoleChange,
            handleFileChange,
            handleFileRemove,
            submitForm,
            resetRegisterForm,
      }
}
